package FileHandling;

import Map.Constants;
import Map.Mindmap;
import Map.Node;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

/**
 * Provides methods for converting a mindmap to a byte array and back.
 * 
 * @author Lewis Marhin and John Gray-Spence
 */
public class ByteConverter {

    /**
     * Converts a mind map to a byte array.
     * @param m Mindmap object to be converted.
     * @return An array of bytes.
     * @throws IOException Thrown when there is write error.
     */
    protected static byte[] mapToByteArray(Mindmap m) throws IOException {
        ByteArrayOutputStream oStream = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream(oStream);

        for (int i = 0; i < m.getNodeList().length; i++) {
            Node n = m.getNodeList()[i];
            out.writeUTF(n.getDesc());
            out.writeUTF(Integer.toString(n.getXloc()));
            out.writeUTF(Integer.toString(n.getYloc()));
        }
        byte[] b = oStream.toByteArray();
        oStream.close();
        out.close();
        return b;
    }

    /**
     * Converts an array of bytes into a Mindmap object.
     * @param b The array of bytes to be converted.
     * @return A mindmap object.
     * @throws java.io.IOException Exception thrown when there is a read error.
     */
    protected static Mindmap byteArrayToMap(byte[] b) throws IOException {
        ByteArrayInputStream iStream = new ByteArrayInputStream(b);
        DataInputStream in = new DataInputStream(iStream);
        Mindmap m = new Mindmap("loading...", 0, 0);

        for (int i = 0; i < Constants.MAX_NODES; i++)
        {
            m.getNodeList()[i].setDesc(in.readUTF());
            m.getNodeList()[i].setXloc(Integer.parseInt(in.readUTF()));
            m.getNodeList()[i].setYloc(Integer.parseInt(in.readUTF()));
        }
        in.close();
        iStream.close();
        return m;
    }
}
